package com.wx.lambda.gao;

import cn.hutool.core.util.RandomUtil;
import jdk.nashorn.internal.objects.annotations.Constructor;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @description: 自定义流式编程
 * @author: wangxun
 * @createDate: 2021/12/7
 * @version: 1.0
 */
public class MyLambda {
    AtomicInteger flag = new AtomicInteger();

    @Data
    @AllArgsConstructor
    class Person {
        String name;
        int age;
        List<Book> books;


    }

    @Data
    @AllArgsConstructor
    class Book {
        String name;
        int pages;
    }

    List<Person> initPersons() {
        List<Person> people = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            people.add(new Person(RandomUtil.randomString(4), i, Arrays.asList(new Book(RandomUtil.randomString(4), flag.incrementAndGet()),new Book(RandomUtil.randomString(4), flag.incrementAndGet()))));

        }
        return people;
    }

    public static void main(String[] args) {
        MyLambda myLambda = new MyLambda();
        List<Person> people = myLambda.initPersons();

        // 获取 年龄大于18 书名 的列表

        Set<String> names = new HashSet<>();

        for (Person person : people) {
            if (person.age > 18) {
                for (Book book : person.getBooks()) {
                    names.add(book.getName());
                }
            }
        }
        Iterator<String> iterator = names.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

        System.out.println("==========================");

        // 流式
        people.stream().filter(person -> person.getAge() > 18)
                .map(person -> person.getBooks())
                .flatMap(books -> books.stream())
                .map(book -> book.getName())
                .forEach(name -> System.out.println(name));



    }
}
